﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using SurfaceAd.Common;
using Windows.Graphics.Display;
using Windows.Security.ExchangeActiveSyncProvisioning;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.System.Profile;
using Windows.UI.Xaml;

/**
 * 创建时间：2014/9/23 14:15:08
 * 作者：yong.blackcore
 * Email：itblackhole@outlook.com
 * QQ：50404503
 */
namespace SurfaceAd.Entities
{
    internal sealed class DeviceInformation
    {
        #region ******************************Navigate******************************
        public string NavigateAppCodeName { get; set; }
        public string NavigateAppName { get; set; }
        public string NavigateAppVersion { get; set; }
        public string NavigatePlatform { get; set; }
        public string NavigateLanguage { get; set; }

        [Obsolete("请使用DeviceUserAgentByWebView属性")]
        public string NavigateUserAgent { get; set; }
        public string NavigateSystemLanguage { get; set; }
        public string NavigateOnLine { get; set; }
        public string NavigateCookieEnabled { get; set; }
        #endregion ******************************Navigate******************************

                
        #region ******************************设备信息******************************
        public double ScreenWidth { get; private set; }
        public double ScreenHeight { get; private set; }
        public string ScreenSize { get; private set; }
        public string ScreenOrientation { get; private set; }

        public String DeviceAdvertisingId { get; private set; }
        public String DeviceASHWID { get; private set; }

        /// <summary>
        /// <para>设备唯一ID</para>
        /// <para>优先获取广告ID，再获取设备的标识符ASHWID</para>
        /// <para>有网卡ID,但现在没有使用</para>
        /// </summary>
        public String DeviceUniqueId { get; private set; }
        /// <summary>
        /// 自定义的UserAgent
        /// <para>执行GetDeviceCustomerUserAgent()方法后才有值</para>
        /// </summary>
        public String DeviceCustomerUserAgent { get; private set; }

        public String DeviceUserAgentByWebView { get; set; }

        /// <summary>
        /// 设备操作系统
        /// <para>只有Windows Phone</para>
        /// <para>执行GetDeviceCustomerUserAgent()方法后才有值</para>
        public string DeviceOs { get; set; }

        /// <summary>
        /// 设备操作系统版本
        /// <para>只能获取到主和次版本号，再细的获取不到了</para>
        /// <para>执行GetDeviceCustomerUserAgent()方法后才有值</para>
        public string DeviceOsVersion { get; set; }

        public String ClientDeviceInfoFriendlyName
        {
            get
            {
                return new EasClientDeviceInformation().FriendlyName.ToString();
            }
        }
        public String ClientDeviceInfoManufacturer
        {
            get
            {
                return new EasClientDeviceInformation().SystemManufacturer.ToString();
            }
        }
        public String ClientDeviceInfoProductName
        {
            get
            {
                return new EasClientDeviceInformation().SystemProductName.ToString();
            }
        }

        public String ClientDeviceInfoSystemSku
        {
            get
            {
                return new EasClientDeviceInformation().SystemSku.ToString();
            }
        }

        public String ClientDeviceInfoOperatingSystem
        {
            get
            {
                return new EasClientDeviceInformation().OperatingSystem.ToString();
            }
        }
        #endregion ******************************设备信息******************************

        public DeviceInformation()
        {
            this.ScreenHeight = this.GetScreenSizeHeight();
            this.ScreenWidth = this.GetScreenSizeWidth();
            this.ScreenSize = this.GetScreenSize();
            this.ScreenOrientation = this.GetScreenOrientation();
            //
            this.DeviceASHWID = GetASHWID();
            this.DeviceAdvertisingId = GetAdvertisingId();
            this.DeviceUniqueId = GetDeviceUniqueId();
        }

        #region ******************************屏幕尺寸方向******************************
        public String GetScreenOrientation()
        {
            try
            {
                DisplayOrientations currentOrientation = DisplayInformation.GetForCurrentView().CurrentOrientation;
                return currentOrientation.ToString();
            }
            catch { return string.Empty; }
        }

        public String GetScreenSize()
        {
            Double width = 0, height = 0;
            try
            {
                height = Window.Current.Bounds.Height;
                width = Window.Current.Bounds.Width;
            }
            catch { }
            return String.Concat(width.ToString(), "*", height.ToString());
        }

        public Double GetScreenSizeHeight()
        {
            Double height = 0;
            try
            {
                height = Window.Current.Bounds.Height;
            }
            catch
            {
            }
            return height;
        }

        public Double GetScreenSizeWidth()
        {
            Double width = 0;
            try
            {
                width = Window.Current.Bounds.Width;
            }
            catch
            {
            }
            return width;
        }
        #endregion ******************************屏幕尺寸方向******************************


        #region ******************************设备唯一标识******************************
        /// <summary>
        /// 优先获取广告ID，再获取设备的标识符ASHWID
        /// <para>有网卡ID,但现在没有使用</para>
        /// </summary>
        public static String GetDeviceUniqueId()
        {
            string deviceUniqueId = GetAdvertisingId();
            if (string.IsNullOrWhiteSpace(deviceUniqueId))
            {
                //无法获取广告ID或为空时，就发送设备ID
                deviceUniqueId = GetASHWID();
            }
            return deviceUniqueId;
        }

        /// <summary>
        /// 获取设备的广告ID
        /// <para>用户关闭选项则为空，模拟器也为空</para>
        /// </summary>
        /// <returns></returns>
        internal static string GetAdvertisingId()
        {
            try
            {
                return Windows.System.UserProfile.AdvertisingManager.AdvertisingId;
            }
            catch { return string.Empty; }
        }

        /// <summary>
        /// ASHWID
        /// <para>http://msdn.microsoft.com/en-us/library/windows/apps/jj553431.aspx</para>
        /// </summary>
        /// <returns></returns>      
        internal static string GetASHWID()
        {
            try
            {
                var token = HardwareIdentification.GetPackageSpecificToken(null);
                IBuffer buffer = token.Id;
                using (var dataReader = DataReader.FromBuffer(buffer))
                {
                    var bytes = new byte[buffer.Length];
                    dataReader.ReadBytes(bytes);
                    string result = BitConverter.ToString(bytes);
                    result = result.Replace("-", "");
                    return result;
                }
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), typeof(DeviceInformation), "GetASHWID");
                return string.Empty;
            }
        }
        #endregion ******************************设备唯一标识******************************


        public void GetDeviceCustomerUserAgent()
        {
            GetDeviceCustomerUserAgent(this.DeviceUserAgentByWebView, this.NavigatePlatform, this.NavigateLanguage);            
        }

        /// <summary>
        /// 通过WebView中取到的UserAgent重新定义为接口需要的UserAgnet
        /// </summary>
        /// <param name="userAgent">
        /// <pre>Mozilla/5.0 (Windows Phone 8.1; ARM; Trident/7.0; Touch; WebView/2.0; rv:11.0; IEMobile/11.0; NOKIA; Nokia 1320) like Gecko</pre>
        /// <pre>5.0 (Windows Phone 8.1; ARM; Trident/7.0; Touch; WebView/2.0; rv:11.0; IEMobile/11.0; NOKIA; Nokia 1320) like Gecko</pre>
        /// </param>
        /// <returns></returns>
        public void GetDeviceCustomerUserAgent(string userAgent, string navigatePlatform, string language)
        {
            //(Platform;Encryption;Os Version;Language;Device)
            this.DeviceOs = this.ClientDeviceInfoOperatingSystem;
            this.DeviceOsVersion = string.Empty;
            string resultFormat = "({0};{1};{2};{3};{4};)";
            string result = string.Format(resultFormat, navigatePlatform, "N", "N", language, "N");
            if (!string.IsNullOrWhiteSpace(userAgent))
            {
                try
                {
                    int startIndex = userAgent.IndexOf("(");
                    int endIndex = userAgent.LastIndexOf(")");
                    if (startIndex >= 0)
                    {
                        string tmp = userAgent.Substring(startIndex + 1, endIndex - (startIndex + 1));
                        if (!string.IsNullOrWhiteSpace(tmp))
                        {
                            //Windows Phone 8.1; ARM; Trident/7.0; Touch; WebView/2.0; rv:11.0; IEMobile/11.0; NOKIA; Nokia 1320
                            string[] items = tmp.Split(';');
                            if (items != null && items.Length == 9)
                            {
                                string osVersion = items[0], deviceType = items[8];
                                if (!string.IsNullOrWhiteSpace(osVersion))
                                {
                                    osVersion = osVersion.Trim();
                                    try
                                    {
                                        var match = Regex.Match(osVersion, @"Windows\s+Phone\s+(\d+(\.\d+)?)");
                                        if (match.Success)
                                        {
                                            if (match.Groups != null && match.Groups.Count > 1)
                                                this.DeviceOsVersion = Convert.ToString(match.Groups[1]);// match.Value;
                                        }
                                    }
                                    catch { }
                                }
                                if (!string.IsNullOrWhiteSpace(deviceType))
                                    deviceType = deviceType.Trim();
                                result = string.Format(resultFormat, navigatePlatform, "N", osVersion, language, deviceType);

                            }
                        }
                    }
                }
                catch (Exception err)
                {
                    LogHelper.LogError(err.ToString(), typeof(DeviceInformation), "GetDeviceCustomerUserAgent");
                }
            }
            this.DeviceCustomerUserAgent = result;
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("DeviceInformation");
            //
            sb.AppendLine("Navigate：");
            sb.Append("NavigateAppCodeName=").Append("\t").AppendLine(NavigateAppCodeName);
            sb.Append("NavigateAppName=").Append("\t").AppendLine(NavigateAppName);
            sb.Append("NavigateAppVersion=").Append("\t").AppendLine(NavigateAppVersion);
            sb.Append("NavigatePlatform=").Append("\t").AppendLine(NavigatePlatform);
            sb.Append("NavigateLanguage=").Append("\t").AppendLine(NavigateLanguage);
            sb.Append("NavigateUserAgent=").Append("\t").AppendLine(NavigateUserAgent);
            sb.Append("NavigateSystemLanguage=").Append("\t").AppendLine(NavigateSystemLanguage);
            sb.Append("NavigateOnLine=").Append("\t").AppendLine(NavigateOnLine);
            sb.Append("NavigateCookieEnabled=").Append("\t").AppendLine(NavigateCookieEnabled);
            //
            sb.AppendLine("Screen：");
            sb.Append("ScreenHeight=").Append("\t").AppendLine(this.ScreenHeight.ToString());
            sb.Append("ScreenWidth=").Append("\t").AppendLine(this.ScreenWidth.ToString());
            sb.Append("ScreenSize=").Append("\t").AppendLine(this.ScreenSize);
            sb.Append("ScreenOrientation=").Append("\t").AppendLine(this.ScreenOrientation);
            //
            sb.AppendLine("Device：");
            sb.Append("DeviceUserAgentByWebView=").Append("\t").AppendLine(this.DeviceUserAgentByWebView.ToString());
            sb.Append("DeviceCustomerUserAgent=").Append("\t").AppendLine(this.DeviceCustomerUserAgent);
            sb.AppendLine("Device：");
            sb.Append("ClientDeviceInfoFriendlyName=").Append("\t").AppendLine(this.ClientDeviceInfoFriendlyName.ToString());
            sb.Append("ClientDeviceInfoManufacturer=").Append("\t").AppendLine(this.ClientDeviceInfoManufacturer.ToString());
            sb.Append("ClientDeviceInfoOperatingSystem=").Append("\t").AppendLine(this.ClientDeviceInfoOperatingSystem.ToString());
            sb.Append("ClientDeviceInfoProductName=").Append("\t").AppendLine(this.ClientDeviceInfoProductName.ToString());
            sb.Append("ClientDeviceInfoSystemSku=").Append("\t").AppendLine(this.ClientDeviceInfoSystemSku.ToString());
            //
            return sb.ToString();
        }

    }
}
